<!--
 * @Descripttion: 编辑砍价活动
 * @Author: xiao li
 * @Date: 2021-01-19 09:44:47
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-23 15:44:33
-->

<template>
  <div class="lb-goods-edit-bargain">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="form-search">
      <div style="height: 40px"></div>
      <el-form
        @submit.native.prevent
        :model="subForm"
        ref="subForm"
        :rules="subFormRules"
        label-width="120px"
      >
        <el-form-item label="活动名称" prop="title">
          <el-input
            v-model="subForm.title"
            maxlength="20"
            show-word-limit
            placeholder="请输入活动名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动商品" prop="goods_id">
          <el-tag
            :type="atv_status > 1 ? 'info' : ''"
            :closable="cur_info.name && atv_status < 2 ? true : false"
            @close="delCurInfo"
            @click="getTableDataList(1)"
            style="cursor: pointer"
            >{{ cur_info.name || '请选择活动商品' }}</el-tag
          >
          <lb-tool-tips
            >砍价活动商品不与任何店内活动共享，例如满减、分销返佣、会员折扣等</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="活动规格" prop="spe">
          <el-tag
            @click="showSpecList"
            :type="atv_status > 1 ? 'info' : ''"
            style="cursor: pointer"
            >请选择商品规格</el-tag
          >
        </el-form-item>
        <el-form-item label="" prop="">
          <el-table
            :data="multipleSelection"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            style="width: 800px"
          >
            <el-table-column
              prop="true_id"
              label="ID"
              width="120"
            ></el-table-column>
            <el-table-column prop="title" label="砍价规格"></el-table-column>
            <el-table-column prop="low_stock" label="砍价库存">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.low_stock"
                  :controls="false"
                  :precision="0"
                  :min="1"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="low_price" label="砍价底价">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.low_price"
                  :controls="false"
                  :precision="2"
                  :min="0"
                ></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="活动时间" prop="range">
          <el-date-picker
            v-model="range"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            value-format="timestamp"
            :disabled="atv_status > 1 ? true : false"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="砍价有效期" prop="over_time">
          <el-input
            placeholder="请输入1-720之间的整数"
            v-model="subForm.over_time"
          >
            <template slot="append">小时</template>
          </el-input>
          <lb-tool-tips
            >用户自发起砍价到砍价截止到时间，取值范围1-720小时</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="帮砍人数" prop="user_num">
          <el-input-number
            style="width: 400px"
            class="lb-input-number"
            v-model="subForm.user_num"
            :controls="false"
            :precision="0"
            :min="2"
            :max="100"
            placeholder="请输入2-100之间的整数"
          ></el-input-number>
          <lb-tool-tips
            >每个砍价订单的帮砍人数，达到该人数才可砍至底价</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="发起砍价次数" prop="start_atv_times">
          <el-input
            placeholder="请输入大于0的整数"
            v-model="subForm.start_atv_times"
          >
            <template slot="append">次/人</template>
          </el-input>
          <lb-tool-tips
            >砍价底价购买时，成功购买该商品算一次，次数不超过商家设置的活动库存即可</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="帮砍次数" prop="atv_times">
          <el-input
            placeholder="请输入1-100之间的整数"
            v-model="subForm.atv_times"
          >
            <template slot="append">次/人</template>
          </el-input>
          <lb-tool-tips
            >每个用户可帮好友砍价的次数，单个活动仅限帮砍一次，最多100次</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="帮砍金额" prop="is_random">
          <el-radio-group v-model="subForm.is_random">
            <el-radio :label="0">均分金额</el-radio>
            <el-radio :label="1">随机金额</el-radio>
          </el-radio-group>
          <lb-tool-tips>每个用户可帮好友砍价的金额数字</lb-tool-tips>
        </el-form-item>
        <el-form-item label="原价购买" prop="buy_must">
          <el-radio-group v-model="subForm.buy_must">
            <el-radio :label="0">{{ $t('action.ON') }}</el-radio>
            <el-radio :label="1">{{ $t('action.OFF') }}</el-radio>
          </el-radio-group>
          <lb-tool-tips>选择开启，则该商品可通过原价购买</lb-tool-tips>
        </el-form-item>
        <el-form-item label="参与必授权" prop="auth">
          <el-checkbox-group @change="changeCheckBox" v-model="checkList">
            <div
              v-for="(item, index) in authList"
              :key="index"
              :style="{
                display: 'inline-block',
                marginLeft: index === 0 ? 0 : '15px'
              }"
            >
              <el-checkbox :label="item.title"></el-checkbox>
              <lb-tool-tips v-if="item.tips">{{ item.tips }}</lb-tool-tips>
            </div>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="活动规则" prop="text">
          <el-input
            type="textarea"
            :rows="8"
            v-model="subForm.text"
            placeholder="请输入活动规则"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 选择可用商品 -->
    <el-dialog
      title="选择可用商品"
      :visible.sync="showGoodsDialog"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
    >
      <div class="dialog-link-box">
        <div class="link-right" :style="{ width: '100%' }">
          <el-form @submit.native.prevent :inline="true" :model="searchForm">
            <el-form-item label>
              <el-input
                v-model="searchForm.title"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
            <el-form-item label>
              <lb-button type="primary" @click="handleCurrentChange(1)">{{
                $t('action.search')
              }}</lb-button>
            </el-form-item>
          </el-form>
          <el-table
            v-loading="loading"
            :data="goods_list"
            ref="singleTable"
            highlight-current-row
            @current-change="handleCurrentRow"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="name" label="商品名称"></el-table-column>
            <el-table-column prop="cover" label="封面图">
              <template slot-scope="scope">
                <lb-image :src="scope.row.cover[0]" />
              </template>
            </el-table-column>
            <el-table-column
              prop="cate_text"
              label="所属分类"
            ></el-table-column>
            <el-table-column prop="price_text" label="价格"></el-table-column>
            <!-- <el-table-column prop="sale_count" label="累计净销量"></el-table-column> -->
            <el-table-column prop="stock" label="库存">
              <template slot-scope="scope">
                {{ scope.row.stock > 0 ? scope.row.stock : '暂无库存' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <lb-page
        :batch="false"
        :page="searchForm.page"
        :pageSize="searchForm.limit"
        :total="total"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      ></lb-page>

      <div style="text-align: right; margin-top: 20px">
        <el-button @click="showGoodsDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitGoodsDialogForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 选择商品规格 -->
    <el-dialog
      title="选择商品规格"
      :visible.sync="showSpecDialog"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
    >
      <div class="dialog-link-box">
        <div class="link-right" :style="{ width: '100%' }">
          <el-table
            v-loading="loading"
            :data="spec_list"
            ref="multipleTable"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column
              type="selection"
              width="55"
              :selectable="selectable"
            ></el-table-column>
            <el-table-column
              prop="true_id"
              label="ID"
              width="80"
            ></el-table-column>
            <el-table-column
              prop="title"
              label="规格组合名称"
            ></el-table-column>
            <el-table-column prop="low_stock" label="砍价库存" width="220">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.low_stock"
                  :precision="0"
                  :min="1"
                  :max="scope.row.stock"
                  v-show="scope.row.stock > 0"
                ></el-input-number>
                <div v-show="scope.row.stock < 1">暂无数据</div>
              </template>
            </el-table-column>
            <el-table-column prop="low_price" label="砍价底价" width="220">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.low_price"
                  :controls="false"
                  :precision="2"
                  :min="0"
                  :max="scope.row.max_price"
                  v-show="scope.row.stock > 0"
                ></el-input-number>
                <div v-show="scope.row.stock < 1">暂无数据</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div style="text-align: right; margin-top: 20px">
        <el-button @click="showSpecDialog = false">取 消</el-button>
        <el-button type="primary" @click="handleSpecConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    let validatePrice = (rule, value, callback) => {
      if (!/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value) || value < 0.01) {
        callback(new Error('请输入正确的数字，最多保留两位小数'))
      } else {
        callback()
      }
    }
    let validateUserNum = (rule, value, callback) => {
      if (!/^\+?[1-9]\d*$/.test(value) || value * 1 > 100 || value * 1 < 1) {
        callback(new Error('请输入2-100之间的整数'))
      } else {
        callback()
      }
    }
    let validateRange = (rule, value, callback) => {
      if (!this.range) {
        callback(new Error('请选择活动时间'))
      } else {
        callback()
      }
    }
    let validateSpe = (rule, value, callback) => {
      if (this.multipleSelection.length < 1) {
        callback(new Error('请选择商品规格'))
      } else {
        callback()
      }
    }
    let validateTime = (rule, value, callback) => {
      if (!/^\+?[1-9]\d*$/.test(value)) {
        callback(new Error('请输入大于0的整数'))
      } else {
        callback()
      }
    }
    let validateOverTime = (rule, value, callback) => {
      if (!/^\+?[1-9]\d*$/.test(value) || value * 1 > 720) {
        callback(new Error('请输入1-720之间的整数'))
      } else {
        callback()
      }
    }
    let validateAtvTime = (rule, value, callback) => {
      if (!/^\+?[1-9]\d*$/.test(value) || value * 1 > 100) {
        callback(new Error('请输入1-100之间的整数'))
      } else {
        callback()
      }
    }
    let validateAuth = (rule, value, callback) => {
      if (this.subForm.name_auth === 0 && this.subForm.mobile_auth === 0) {
        callback(new Error('请选择参与必授权'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      navTitle: '',
      courseList: [],
      authTips: '选中后授权所选内容才能参与活动',
      checkList: [],
      authList: [
        {
          title: '微信信息/头像',
          key: 'name_auth'
        },
        {
          title: '手机号',
          key: 'mobile_auth',
          tips: '用户需授权所选内容才能发起砍价活动'
        }
      ],
      range: '',
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - (24 * 3600 * 1000)
        }
      },
      showGoodsDialog: false,
      cur_info: {
        id: 0,
        name: ''
      },
      currentRow: {},
      stock: 0,
      searchForm: {
        page: 1,
        limit: 10,
        title: ''
      },
      goods_list: [],
      loading: false,
      total: 0,
      showSpecDialog: false,
      spec_list: [],
      multipleSelection: [],
      selectable (row, index) {
        if (row.stock > 0) {
          return true
        } else {
          return false
        }
      },
      atv_status: 1,
      subForm: {
        id: 0,
        title: '',
        goods_id: '',
        spe: [],
        start_time: 0,
        end_time: '',
        over_time: '',
        user_num: '',
        start_atv_times: '',
        atv_times: '',
        is_random: 0,
        buy_must: 0,
        name_auth: 0,
        mobile_auth: 0,
        text: '',
        status: 1
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入活动名称', trigger: 'blur' },
        goods_id: { required: true, type: 'number', message: '请选择活动商品', trigger: 'blur' },
        stock: { required: true, type: 'number', message: '请输入砍价商品所选规格的库存', trigger: 'blur' },
        low_price: { required: true, validator: validatePrice, trigger: 'blur' },
        range: { required: true, validator: validateRange, trigger: 'blur' },
        spe: { required: true, validator: validateSpe, trigger: 'blur' },
        over_time: { required: true, validator: validateOverTime, trigger: 'blur' },
        user_num: { required: true, validator: validateUserNum, trigger: 'blur' },
        start_atv_times: { required: true, validator: validateTime, trigger: 'blur' },
        atv_times: { required: true, validator: validateAtvTime, trigger: 'blur' },
        auth: { required: true, validator: validateAuth, trigger: 'blur' },
        is_random: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        buy_must: { required: true, type: 'number', message: '请选择', trigger: 'blur' },
        text: { required: true, type: 'string', message: '请输入活动规则', trigger: 'blur' }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    if (id) {
      this.subForm.id = id
      await this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.BargainEdit' : 'menu.BargainAdd')
  },
  methods: {
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.handleCurrentChange(1)
    },
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.getTableDataList()
    },
    /**
     * @method: 商品列表
     */
    async getTableDataList (flag) {
      if (flag) {
        this.searchForm.page = 1
        if (this.atv_status > 1) return
      }
      this.loading = true
      let { code, data } = await this.$api.getBaseGoodsSelect(this.searchForm)
      this.loading = false
      if (code !== 200) return
      this.goods_list = data.data
      this.total = data.total
      this.showGoodsDialog = true
    },
    /**
     * @method: 规格列表
     */
    async getSpecList () {
      let { goods_id: gid } = this.subForm
      if (!gid) {
        this.$message.error(`请选择活动商品`)
        return
      }
      let { code, data } = await this.$api.getBaseGoodsSpeList({ goods_id: gid })
      this.loading = false
      if (code !== 200) return
      data.price.map(item => {
        item.price = item.price * 1
        item.max_price = (item.price * 1 - 0.01).toFixed(2)
        item.low_price = (item.price * 1 - 0.01).toFixed(2)
        item.low_stock = item.stock * 1
        this.multipleSelection.map(aitem => {
          if (aitem.id === item.id) {
            item.max_price = aitem.max_price
            item.low_price = aitem.low_price
            item.low_stock = aitem.low_stock
          }
        })
      })
      this.spec_list = data.price
      this.showSpecDialog = true
    },
    /**
     * @method: 删除当前选择商品
     */
    delCurInfo () {
      if (this.atv_status > 1) return
      this.cur_info = { id: 0, name: '' }
      this.subForm.goods_id = 0
      this.subForm.spe = []
      this.multipleSelection = []
    },
    /**
     * @method: 商品-单选
     * @param {*} e
     */
    handleCurrentRow (e) {
      this.currentRow = e
    },
    /**
     * @method: 关联商品-确定
     */
    submitGoodsDialogForm () {
      let { id, name, stock } = this.currentRow
      if (!stock) {
        this.$message.error(`此商品暂无库存，请选择其他商品`)
        return
      }
      if (!id) {
        this.$message.error(`请选择活动商品`)
        return
      }
      this.cur_info = { id, name }
      this.subForm.goods_id = id
      this.currentRow = {}
      if (this.multipleSelection.length > 0 && id !== this.multipleSelection[0].goods_id) {
        this.multipleSelection = []
      }
      this.showGoodsDialog = false
    },
    /**
     * @method: 打开规格弹窗
     */
    async showSpecList () {
      if (this.atv_status > 1) return
      await this.getSpecList()
      let arr = []
      this.multipleSelection.map((item) => {
        arr.push(item.true_id)
      })
      this.spec_list.map((item) => {
        if (arr.includes(item.true_id)) {
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        }
      })
    },
    /**
     * @method: 规格-多选
     * @param {*} val
     */
    handleSelectionChange (val) {
      let arr = []
      val.map((item) => {
        arr.push(item.id)
      })
      this.spec_list.map((bitem, bindex) => {
        this.spec_list[bindex].check = false
        if (arr.includes(bitem.id)) {
          this.spec_list[bindex].check = true
        }
      })
    },
    /**
     * @method: 关联规格-确定
     */
    handleSpecConfirm () {
      let data = []
      this.spec_list.map((item) => {
        if (item.check) {
          item.goods_id = this.subForm.goods_id
          data.push(item)
        }
      })
      if (!this.subForm.id) {
        if (this.multipleSelection.length > 0 && data.length < 1) {
          this.$confirm(`当前无选择规格，请确认是否要清空选项？`, this.$t('tips.reminder'), {
            confirmButtonText: this.$t('action.comfirm'),
            cancelButtonText: this.$t('action.cancel'),
            type: 'warning'
          }).then(() => {
            this.multipleSelection = data
            this.showSpecDialog = false
          }).catch(() => {
          })
        } else {
          this.multipleSelection = data
          this.showSpecDialog = false
        }
      } else {
        if (data.length < 1) {
          this.$message.error(`请选择商品规格`)
          return
        }
        this.multipleSelection = data
        this.showSpecDialog = false
      }
    },
    /**
     * @method: 多选框
     * @param {*} e
     */
    changeCheckBox (e) {
      this.authList.map(item => {
        this.subForm[item.key] = e.includes(item.title) ? 1 : 0
      })
    },
    /**
     * @method: 砍价活动详情
     * @param {*} id
     */
    async getDetail (id) {
      let { code, data } = await this.$api.bargainInfo({ id })
      if (code !== 200) return
      let checkItem = []
      this.authList.map(item => {
        if (data[item.key] === 1) {
          checkItem.push(item.title)
        }
      })
      this.checkList = checkItem
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
      this.range = [data.start_time * 1000, data.end_time * 1000]
      this.cur_info = {
        id: data.goods_id,
        name: data.goods_name
      }
      data.spe.map(item => {
        item.goods_id = item.goods_id
        item.true_id = item.spe_id
        item.title = item.spe_name
        item.low_stock = item.stock
      })

      this.multipleSelection = data.spe
      this.atv_status = data.atv_status
    },
    /**
     * @method: 新增/编辑
     */
    submitInfo () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        let { range = '' } = this
        if (range) {
          subForm.start_time = range[0] / 1000
          subForm.end_time = range[1] / 1000
        }
        let specs = []
        this.multipleSelection.map(item => {
          specs.push({ goods_id: item.goods_id, spe_id: item.true_id, stock: item.low_stock, low_price: item.low_price })
        })
        subForm.spe = specs
        let modelMethod = subForm.id ? 'bargainUpdate' : 'bargainAdd'
        this.$api[modelMethod](subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
            this.$router.back(-1)
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-goods-edit-bargain {
  width: 100%;
  .form-search {
    padding: 20px;
    .el-form {
      width: 100%;
      .el-form-item {
        margin-bottom: 24px;
        .el-select,
        .el-input {
          width: 400px;
        }
        .el-textarea {
          width: 600px;
        }
      }
    }
  }
}
</style>
